<!-- src/App.vue -->
<template>
  <div class="app">
    <router-view v-slot="{ Component }">
      <keep-alive :include="['Home', 'Follow', 'Message', 'My']">
        <component :is="Component" />
      </keep-alive>
    </router-view>
    <TabBar v-if="showTabbar" />
    <!-- 全局登录弹窗 -->
    <LoginModal v-model="showLoginModal" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, defineAsyncComponent, inject, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const socket = inject('socket')
import { useUserStore } from '@/stores/userinfo'
const userStore = useUserStore()
const userID = computed(() => userStore.userInfo?.userId || '')

// Socket连接状态
const socketConnected = ref(false)

// 互动数据
import { useInteractionStore } from '@/stores/interaction'
const interactionStore = useInteractionStore()

const showTabbar = computed(() => {
  return route.meta.showTabbar
})

// 登录弹窗控制
const showLoginModal = ref(false)
const LoginModal = defineAsyncComponent(() => import('@/components/authentication/LoginModal.vue'))
const handleReceiveComment = (data) => {
  console.log('🔔 收到新评论通知:', data)
  // 这里可以做：弹窗提醒、更新未读数、自动刷新评论等
  // 刷新评论数
  const { toVideoOwnerId } = data
  interactionStore.fetchCommentCount(toVideoOwnerId ? toVideoOwnerId : userID.value)
  // 打印评论数
  console.log('评论数:', interactionStore.commentCount)
}
const handleReceiveTriggerFollow = (data) => {
  console.log('🔔 收到新关注通知:', data)
  const { toUserId } = data
  // 刷新关注数
  interactionStore.fetchFollowerCount(toUserId ? toUserId : userID.value)
  // 打印关注数
  console.log('关注数:', interactionStore.followerCount)
}
const handleReceiveTriggerLike = (data) => {
  console.log('🔔 收到新点赞通知:', data)
  const { toUserId } = data
  // 刷新点赞数
  interactionStore.fetchLikeCount(toUserId ? toUserId : userID.value)
  // 打印点赞数
  console.log('点赞数:', interactionStore.likeCount)
}
const handleReceiveFriend = (data) => {
  console.log('🔔 收到新好友通知:', data)
  const { toUserId } = data
  // 刷新@评论数
  interactionStore.fetchAtCommentCount(toUserId ? toUserId : userID.value)
  // 打印@评论数
  console.log('@评论数:', interactionStore.atCommentCount)
}
// 监听全局登录事件
const handleShowLogin = (event) => {
  // 如果有重定向路径，保存到路由查询参数中
  if (event.detail && event.detail.redirect) {
    const currentRoute = router.currentRoute.value
    // 只有当当前路由不包含重定向参数时才添加
    if (!currentRoute.query.redirect) {
      router.replace({
        query: { ...currentRoute.query, redirect: event.detail.redirect }
      })
    }
  }
  showLoginModal.value = true
}

// 设置socket连接和事件监听器
const setupSocketConnection = () => {
  if (!userID.value) return

  console.log('🔌 正在为用户建立socket连接:', userID.value)

  // 监听socket连接事件
  socket.on('connect', () => {
    console.log('✅ Socket连接成功:', socket.id)
    socketConnected.value = true
  })

  // 监听socket断开连接事件
  socket.on('disconnect', () => {
    console.log('❌ Socket连接断开')
    socketConnected.value = false
  })

  // 监听socket连接错误
  socket.on('connect_error', (error) => {
    console.error('🚫 Socket连接错误:', error)
    socketConnected.value = false
  })


  // 发送登录事件
  socket.emit('login', userID.value)
  console.log('📤 已发送登录事件，用户ID:', userID.value)

  // 移除之前的事件监听器，防止重复绑定
  socket.off('receiveComment', handleReceiveComment)
  socket.off('receiveTriggerFollow', handleReceiveTriggerFollow)
  socket.off('receiveTriggerLike', handleReceiveTriggerLike)
  socket.off('receiveFriend', handleReceiveFriend)



  // 监听评论事件
  socket.on('receiveComment', (data) => {
    console.log('🔔 收到新评论通知:', data)
    handleReceiveComment(data)
  })

  // 监听关注事件
  socket.on('receiveTriggerFollow', (data) => {
    console.log('🔔 收到新关注通知:', data)
    handleReceiveTriggerFollow(data)
  })

  // 监听点赞事件
  socket.on('receiveTriggerLike', (data) => {
    console.log('🔔 收到新点赞通知:', data)
    handleReceiveTriggerLike(data)
  })
  // 监听好友事件
  socket.on('receiveFriend', (data) => {
    console.log('🔔 收到新好友通知:', data)
    handleReceiveFriend(data)
  })


  console.log('👂 已设置所有事件监听器')
}

// 监听用户ID变化，当用户登录时立即建立socket连接
watch(userID, (newUserId) => {
  if (newUserId) {
    setupSocketConnection()
  }
}, { immediate: true })

onMounted(() => {

  window.addEventListener('show-login', handleShowLogin)
  // 添加页面关闭前的事件监听
  window.addEventListener('beforeunload', handleBeforeUnload)
  // 如果用户已登录，立即建立socket连接
  if (userID.value) {
    setupSocketConnection()
  }
})

onUnmounted(() => {
  socket.off('receiveComment', handleReceiveComment)
  window.removeEventListener('show-login', handleShowLogin)
  window.removeEventListener('beforeunload', handleBeforeUnload)
  // userStore 重置用户信息
  userStore.clearUserInfo()
})

// 处理页面关闭前的事件
const handleBeforeUnload = () => {
  console.log('用户正在关闭应用，清理用户信息')
  userStore.clearUserInfo()
}

import TabBar from './components/common/TabBar.vue'
</script>

<style>
.app {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.debug-info {
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px;
  font-size: 12px;
  z-index: 9999;
  border-radius: 0 0 5px 0;
}

.debug-info p {
  margin: 0 0 5px 0;
}
</style>